import React, { Component } from 'react'
import { Map, List, fromJS } from 'immutable'
export default class App extends Component {
  state = {
    // fromJS 全部转换为 Immutable
    info: fromJS({
      name: 'ifer',
      address: {
        province: '河南',
        city: '周口',
      },
      favor: ['吃饭', '睡觉'],
    }),
  }
  updateName = () => {
    this.setState({
      info: this.state.info.set('name', 'elser'),
    })
  }
  updateCity = () => {
    this.setState({
      // 使用 setIn、NB
      info: this.state.info.setIn(['address', 'city'], '淮阳'),
    })
  }
  delItem = (index) => {
    this.setState({
      // 修改数组里面的第 0 项为 'xxx'
      // info: this.state.info.setIn(['favor', 0], 'xxx'),
      /* info: this.state.info.updateIn(['favor'], (list) =>
          list.splice(index, 1)
      ), */
      info: this.state.info.update('favor', (list) => list.splice(index, 1)),
    })
  }
  render() {
    return (
      <div>
        <div>
          name: {this.state.info.get('name')}
          <button onClick={this.updateName}>修改</button>
        </div>
        <div>
          address:{' '}
          {this.state.info.get('address').get('province') +
            '~' +
            this.state.info.get('address').get('city')}
          <button onClick={this.updateCity}>修改</button>
        </div>
        <ul>
          {this.state.info.get('favor').map((item, index) => (
            <li key={item}>
              {item}
              <button onClick={() => this.delItem(index)}>x</button>
            </li>
          ))}
        </ul>
      </div>
    )
  }
}
